package com.atguigu.chap03;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class ShareDataOne {
    private int data = 0;
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //判断
        /*if (data != 0) {  //导致虚假唤醒
            wait();
        }*/
            //通过while循环判断解决虚假唤醒问题
            while (data != 0) {
                condition.await();
            }


            data++;
            System.out.println(Thread.currentThread().getName() + "\t" + "---come in data=" + data);

            //通知
            condition.signal();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //判断
        /*if (data != 1) {
            wait();
        }*/
            while (data != 1) {
                condition.await();
            }

            //干活
            data--;
            System.out.println(Thread.currentThread().getName() + "\t" + "---come in data=" + data);

            //通知
            condition.signal();
            // condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}

public class WaitNotifyDemo {

    public static void main(String[] args) {
        ShareDataOne shareDataOne = new ShareDataOne();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareDataOne.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "A").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareDataOne.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareDataOne.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    shareDataOne.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "D").start();
    }
}
